package com.swz.dcrm.ui.home;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.swz.dcrm.adpter.CarOrderAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.CarOrder;
import com.swz.dcrm.model.Clue;
import com.swz.dcrm.model.Order;
import com.swz.dcrm.model.PageResponse;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CarManagementViewModel;
import com.swz.dcrm.util.CustomDecoration;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class OrderFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;


    private int page=1;
    private int size=15;
    private long total;
    Clue clue;
    @Inject
    CarManagementViewModel carManagementViewModel;
    private CarOrderAdapter carOrderAdapter;
    public static OrderFragment newInstance() {

        return new OrderFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())){
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }

        carManagementViewModel.getCarOrders(clue.getId(),page,size)
                .observe(this, orderPageResponse -> {
                    if(orderPageResponse==null){
                        return;
                    }
                    smartRefreshLayout.setEnableLoadmore(true);
                    smartRefreshLayout.finishRefresh();
                    smartRefreshLayout.finishLoadmore();
                    if(orderPageResponse.isSuccess()){
                        total = orderPageResponse.getTotal();
                        if(carOrderAdapter==null){
                            carOrderAdapter=new CarOrderAdapter(getContext(),orderPageResponse.getData(),clue);
                            carOrderAdapter.setOnButtonClickListener(onButtonClickListener);
                            rv.setAdapter(carOrderAdapter);
                        }else {
                            carOrderAdapter.refresh(orderPageResponse.getPage(),orderPageResponse.getData());
                        }
                    }
                });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public int layoutId() {
        return R.layout.fragment_order;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.addItemDecoration(new CustomDecoration(getContext(),10,0,10,10));
        title.setText(getString(R.string.order_title));
        tvRight.setText(getString(R.string.order_new));
        OrderFragmentArgs orderFragmentArgs=OrderFragmentArgs.fromBundle(getArguments());
        if(!orderFragmentArgs.getClueId().equals("test")){
             clue=new Gson().fromJson(orderFragmentArgs.getClueId(),Clue.class);
        }
        smartRefreshLayout.setOnRefreshListener(refreshlayout -> {
            smartRefreshLayout.setEnableLoadmore(true);
            page=1;
            onLoadRetry();
        });
        smartRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            if (carOrderAdapter != null && carOrderAdapter.getItemCount() >= total) {

                smartRefreshLayout.finishLoadmore();
                smartRefreshLayout.setEnableLoadmore(false);
                return;
            } else {
                page++;
                onLoadRetry();
            }
        });
        onLoadRetry();
        return true;
    }


    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }
    @OnClick(R.id.tv_right)
    public void add(){
        AddOrderFragmentArgs.Builder builder=new AddOrderFragmentArgs.Builder();
        builder.setClue(new Gson().toJson(clue));
        go(null,R.id.action_orderFragment_to_addOrderFragment,builder.build().toBundle());
    }
    CarOrderAdapter.OnButtonClickListener onButtonClickListener=new CarOrderAdapter.OnButtonClickListener() {
        @Override
        public void onCancelOrder(Order order) {

            ReasonFragmentArgs.Builder builder4=new ReasonFragmentArgs.Builder();
            builder4.setTitle(getString(R.string.clue_detail_cancel_order));
            builder4.setClueId(String.valueOf(order.getId()));
            builder4.setTag(getString(R.string.clue_detail_reason,builder4.getTitle()));
            go(null,R.id.action_orderFragment_to_reasonFragment,builder4.build().toBundle());
        }

        @Override
        public void onDelivery(Order order) {
            showNormalDialog(true, "提示", "是否确定交车", () -> {

                dismissDialog();
            }, () -> {
                carManagementViewModel.deliveryCar(order.getId())
                        .observe(getViewLifecycleOwner(), stringBaseResponse -> {
                            if(stringBaseResponse==null){
                                return;
                            }
                            showToast(stringBaseResponse.getMsg());
                            if(stringBaseResponse.isSuccess()){
                                page=1;
                                onLoadRetry();
                                smartRefreshLayout.setEnableLoadmore(true);
                            }
                        });
                dismissDialog();
            });
        }

        @Override
        public void onItemClick(Order order) {
            AddOrderFragmentArgs.Builder builder=new AddOrderFragmentArgs.Builder();
            builder.setOrderId(String.valueOf(order.getId()));
            go(null,R.id.action_orderFragment_to_addOrderFragment,builder.build().toBundle());
        }
    };
}
